package com.david.concurrent.notify.wait;

import java.util.concurrent.BlockingQueue;

/**
 * @author wade
 * @version 1.0
 * @date 2021/7/19 16:20
 */
public class Producer  implements Runnable{
    private BlockingQueue<String> queue;
    int i=0;

    public Producer(BlockingQueue<String> queue) {
        this.queue=queue;
    }

    @Override
    public void run() {

        while (true){
            synchronized (queue){
                while (queue.size()==20){
                    try {
                        queue.wait();
                        System.out.println("队列已满，生产者等待");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //空闲则生成元素 ， 并通知消费者线程
                String msg="消息"+i++;
                System.out.println("生产者生产了一条消息：" + msg);
                queue.add(msg);
                queue.notifyAll();
            }
        }
    }
}
